package org.internna.ossmoney.mvc;

import java.util.Random;
import javax.inject.Inject;
import org.internna.ossmoney.services.UserService;
import org.internna.ossmoney.model.security.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.UserProfile;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.security.authentication.AuthenticationManager;

import static org.internna.ossmoney.util.SecurityUtils.authenticate;
import static org.internna.ossmoney.util.SecurityUtils.assumeAuthentication;

@Controller
@RequestMapping("/users")
public class UserController {

	@Inject private UserService userService;
	@Inject private AuthenticationManager authenticationManager;

	@RequestMapping(value = "/provider-register", method = RequestMethod.GET)
    public String provider(final WebRequest request) {
		Connection<?> connection = ProviderSignInUtils.getConnection(request);
		if (connection != null) {
			UserProfile profile = connection.fetchUserProfile();
			String userId = profile.getUsername();
			UserDetails user = UserDetails.findUserDetailsByUsername(userId);
			if (user == null) {
				userService.register(userId, String.valueOf(new Random().nextInt()), profile.getName(), profile.getEmail());
			}
			assumeAuthentication(userId);
		}
		return "redirect:/financial/accounts/create";
    }

	@RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
		return "users/register";
    }

	@RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(String username, String password, String name, String email) {
		userService.register(username, password, name, email);
		authenticate(authenticationManager, username, password);
		return "redirect:/financial/accounts/create";
    }

}
